package com.koudai.reader;

import java.util.Calendar;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.AdWallManager;
import com.koudai.reader.conponment.SubmitQuestionDialog;
import com.koudai.reader.util.Constant;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.vo.EndUser;
import com.koudai.reader.vo.Task;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;

public class SettingActivity extends BaseActivity implements UmengUpdateListener {

    private RelativeLayout checkVersion;
    private RelativeLayout contactUs;
    private RelativeLayout scoreRule;
    private RelativeLayout getScore;
    private RelativeLayout rateUs;
    private RelativeLayout sign;
    private RelativeLayout cleanRequest;
    private RelativeLayout share;

    private TextView item_devider_text1;
    private ImageView isVip;

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        item_devider_text1.setText("账号（积分: " + EndUser.getInstance().getGlodStr() + "）");
        isVip = (ImageView) findViewById(R.id.vip);
        if (EndUser.getInstance().isVip()) {
            isVip.setVisibility(View.VISIBLE);
        } else {
            isVip.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        checkVersion = (RelativeLayout) findViewById(R.id.setting_item_version_check);
        contactUs = (RelativeLayout) findViewById(R.id.setting_item_contact_us);

        share = (RelativeLayout) findViewById(R.id.setting_item_share);
        scoreRule = (RelativeLayout) findViewById(R.id.setting_item_score_rule);
        getScore = (RelativeLayout) findViewById(R.id.setting_item_get_score);
        sign = (RelativeLayout) findViewById(R.id.setting_item_sign);
        rateUs = (RelativeLayout) findViewById(R.id.setting_item_rate_us);
        item_devider_text1 = (TextView) findViewById(R.id.item_devider_text1);

        cleanRequest = (RelativeLayout) findViewById(R.id.setting_clean_request);

        handleCheckVersion();

        handleReadSetting();

        handleSocreRule();

        handleGetscore();

        handleRate();

        handleSign();

        handleCleanRequest();

        hanldeShare();
    }

    private void hanldeShare() {
        share.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_SEND);  

                intent.setType("text/plain");  
                intent.putExtra(Intent.EXTRA_SUBJECT, "书海小说分享");  
                intent.putExtra(Intent.EXTRA_TEXT, "相当不错的小说阅读软件，下载地址 http://www.nduoa.com/apk/download/568595?from=ndoo");  
                startActivity(Intent.createChooser(intent, getTitle()));
            }
        });
    }

    private void handleRate() {

        rateUs.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=" + getPackageName()));
                startActivity(intent);

            }
        });
    }

    private void handleCleanRequest() {

        cleanRequest.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                final Dialog dialog = new AlertDialog.Builder(SettingActivity.this).setTitle("温馨提示").setMessage("如果清除的话，您之前搜索不到的小说，如果有更新我们也无法提示您了")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                // TODO 积分墙
                                showWait("处理中");
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {

                                        List<Task> list = HttpUtils.taskList();
                                        if (list.size() == 0) {
                                            handler.post(new Runnable() {

                                                @Override
                                                public void run() {
                                                    Toast.makeText(SettingActivity.this, "暂无搜索请求", Toast.LENGTH_SHORT).show();

                                                }
                                            });
                                        } else {
                                            for (Task task : list) {
                                                HttpUtils.delTask(task.getId());
                                            }

                                            handler.post(new Runnable() {

                                                @Override
                                                public void run() {
                                                    Toast.makeText(SettingActivity.this, "操作完成", Toast.LENGTH_SHORT).show();

                                                }
                                            });
                                        }

                                        waitClose();

                                    }
                                }).start();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                            }
                        }).create();

                dialog.show();
            }
        });
    }

    private ProgressDialog processDialog;

    private void handleSocreRule() {
        scoreRule.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub
                /*
                 * showWait("加载中"); new Thread(new Runnable() {
                 * 
                 * @Override public void run() { // TODO Auto-generated method
                 * stub final String content = HttpUtils.getTerm("2");
                 * waitClose(); handler.post(new Runnable() { public void run()
                 * { new MessageDialog(SettingActivity.this, content).show(); }
                 * });
                 * 
                 * } }).start();
                 */

                Intent intent = new Intent();
                intent.setClass(SettingActivity.this, VipActivity.class);
                SettingActivity.this.startActivity(intent);
            }
        });
    }

    private void handleReadSetting() {

        contactUs.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {

                new SubmitQuestionDialog(SettingActivity.this).show();

            }
        });

    }

    Handler handler = new Handler();

    private void handleSign() {

        sign.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub
                SharedPreferences config = getSharedPreferences("config", 0);
                long lastSign = config.getLong("lastSign", 0);

                if (Calendar.getInstance().getTimeInMillis() - lastSign >= 24 * 60 * 60 * 1000) {
                    config.edit().putLong("lastSign", Calendar.getInstance().getTimeInMillis()).commit();
                    new Thread(new Runnable() {

                        @Override
                        public void run() {

                            if (HttpUtils.goldOperation("sign")) {

                                EndUser.getInstance().updateGold(Constant.operation.get("sign"));
                                handler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        Toast.makeText(SettingActivity.this, "签到成功,恭喜您获得10积分", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }

                        }
                    }).start();
                } else {
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(SettingActivity.this, "今天已经签过到啦", Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        });

    }

    /**
     * 
     */
    private void handleGetscore() {
        getScore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                AdWallManager.openAppOffers(SettingActivity.this);
            }
        });
    }

    private void handleCheckVersion() {
        checkVersion.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                UmengUpdateAgent.update(SettingActivity.this);
                UmengUpdateAgent.setUpdateAutoPopup(false);
                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
                    @Override
                    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                        switch (updateStatus) {
                        case 0:
                            UmengUpdateAgent.showUpdateDialog(SettingActivity.this, updateInfo);
                            break;
                        case 1:
                            Toast.makeText(SettingActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();
                            break;
                        case 2:
                            Toast.makeText(SettingActivity.this, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                            break;
                        case 3:
                            Toast.makeText(SettingActivity.this, "超时", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onUpdateReturned(int arg0, UpdateResponse arg1) {
        // TODO Auto-generated method stub

    }

    /**
     * 带等待图标的等待框 参数message：需要显示给用户的字符串
     * */
    public void showWait(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                processDialog = new ProgressDialog(SettingActivity.this);
                processDialog.setMessage(message);
                processDialog.setIndeterminate(true);
                processDialog.setCancelable(false);
                processDialog.show();

            }
        });

    }

    /**
     * 关闭等待框
     * */
    public void waitClose() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (processDialog != null && processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
        });
    }
}
